#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "comlogin.h"
#include "settlement.h"
#include "comsettlement.h"
#include "calculate.h"
#include "question.h"
#include <QDebug>
#include <QDateTime>
#include <QTimer>
#include <QSound>
#include <QMediaPlayer>
#include <QMessageBox>
#include <QSqlDatabase> //数据驱动
#include <QSqlQuery> //数据库执行语句
#include <QSqlRecord>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //接收登录信息
    connect(comLogin::p_login,SIGNAL(comToMain(QString,QString)),this,SLOT(doProcessLoginRequest(QString,QString)));

    //设置游戏界面的背景图
    this->setFixedSize(800,540);//固定窗口大小
    QPalette pal =this->palette();
    QImage ImgAllbackground(":/images/background.jpg");
    QImage fitimpic = ImgAllbackground.scaled(this->width(),this->height(),Qt::IgnoreAspectRatio);
    pal.setBrush(QPalette::Window,QBrush(fitimpic));
    setPalette(pal);
    //用户头像
    QPixmap *pix = new QPixmap(":/images/head1.png");
    QSize sz = ui->label_image->size();
    ui->label_image->setPixmap(pix->scaled(sz));
    //初始化
    traveler=false;
}

void MainWindow::init(){

    //生成四位随机数
    cal.setNum();
    ui->num1->setText(QString::number(cal.getNum(0),10));
    ui->num2->setText(QString::number(cal.getNum(1),10));
    ui->num3->setText(QString::number(cal.getNum(2),10));
    ui->num4->setText(QString::number(cal.getNum(3),10));
    //初始化countA,countB,resetflag,sum,scores
    countA=0;countB=0;resetflag=false;sum=0;scores=0;
    answerTimes=2;refreshTimes=3;preButton=0;videoFlag=false;
    ui->label_time1->setText(QString::number(refreshTimes));
    ui->tips->setEnabled(true);
    ui->label_time2->setText(QString::number(answerTimes));
    ui->refresh->setEnabled(true);
    ui->score->setText(QString::number(scores));

    //游戏倒计时
    timer = new QTimer(this);
    timer->start(1000);
    connect(timer,&QTimer::timeout,this,&MainWindow::timeoutRun);
    //播放游戏BGM
//    QSound *music = new QSound("D:\\workQt\\Calculate24\\images\\Elements.wav");
//    music->play();
//    music->setLoops(400);
    player = new QMediaPlayer(this);//设置背景音乐
    player->setMedia(QUrl::fromLocalFile("D:\\workQt\\Calculate24\\images\\music.mp3"));
    player->setVolume(20);//音量
    player->play();
    musicFlag = true;
//    connect(ui->actionPlay,&QAction::triggered,[=](){
//           player->play();
//        });//开始播放，也可以用按钮的方式，这里用的是菜单栏中的action
//    connect(ui->actionStop,&QAction::triggered,[=](){
//          player->stop();
//        });//停止播放
    //设置点击音效
    click = new QMediaPlayer(this);
    click->setMedia(QUrl::fromLocalFile("D:\\workQt\\Calculate24\\images\\click.mp3"));
    click->setVolume(30);
    //设置游戏结束音效
    winPlayer = new QMediaPlayer(this);//设置背景音乐
    winPlayer->setMedia(QUrl::fromLocalFile("D:\\workQt\\Calculate24\\images\\win.mp3"));
    winPlayer->setVolume(30);//音量
    //十秒倒计时音效
    countDown = new QMediaPlayer(this);//设置背景音乐
    countDown->setMedia(QUrl::fromLocalFile("D:\\workQt\\Calculate24\\images\\countDown.mp3"));
    countDown->setVolume(100);//音量
}

//数据库初始化
bool MainWindow::mysql_init(){
    QSqlDatabase db;
    QString dsn;
    //先判断是否已经连接
    if(QSqlDatabase::contains("qt_sql_default_connection"))
      db = QSqlDatabase::database("qt_sql_default_connection");
    //没有则连接自己的数据库
    else{
      db = QSqlDatabase::addDatabase("QODBC");
      dsn = "Driver={MySQL ODBC 8.0 UniCode Driver};"; // Driver is now {MySQL}
//          dsn.append("Server=192.168.112.132,3306;"); // IP,Port
          dsn.append("Server=192.168.0.196,3306;"); // IP,Port
          dsn.append("Database=calculate24;"); // Schema
          dsn.append("Uid=root;"); // User
          dsn.append("Pwd=1234;"); // Password
          dsn.append("MULTI_HOST=1;");
          db.setDatabaseName(dsn);
    }
    if(!db.open())
    {
        qDebug()<<"open error";
        return false;
    }
    else{
        return true;
    }
}

//更新数据库用户最高分的函数
void MainWindow::update_hihgestScore(){
    //如果登录失败，结束函数
    if(!mysql_init()){
        return;
    }
    else {
        QString sql=QString("update tb_user set highestScore='%1' where username='%2'")
                .arg(scores).arg(ui->l_username->text());
        //创建执行语句对象
        QSqlQuery query(sql);
        //判断执行结果
        if(!query.exec(sql)){
            qDebug()<<"update error";
        }
        else
        {
            qDebug()<<"update success";
         }
    }
}

//接收登录信息函数
void MainWindow::doProcessLoginRequest(QString s1,QString s2){
    ui->l_username->setText(s1);
    ui->l_score->setText(s2);
    //登录成功加载服务器
    mysql_init();
    //将游客标志设为true,说明现在不是游客登录状态
    traveler = true;
}

void MainWindow::timeoutRun(){
     //定时
     int min = 1;
     for(int sec=30;sec>=0;sec--){
         ui->lcdNumber->display(QDateTime::currentDateTime().toString(
            QString("%1").arg(min, 2, 10, QChar('0'))+":"+
            QString("%1").arg(sec, 2, 10, QChar('0'))));
            Delay_MSec(1000);
            if(min>0 && sec==0){
               sec=59;
               min--;
            }
            else if(min == 0 && sec == 0){
               timer->stop();
               player->stop();
               winPlayer->play();
               emit comToSettlement(scores);
            }
            else if(min==0&&sec==11){
                countDown->play();
            }
     }
     if(scores > ui->l_score->text().toInt() && traveler){
         update_hihgestScore();
     }
     comSettlement::p_settlement->show();
     this->hide();
}

//用于延迟1s，实现倒计时的功能
void MainWindow::Delay_MSec(int msec)
{
    QTime _Timer = QTime::currentTime().addMSecs(msec);
    while(QTime::currentTime() < _Timer ){
        QCoreApplication::processEvents(QEventLoop::AllEvents,100);
    }

}

MainWindow::~MainWindow()
{
    delete ui;
}

//判断得分
bool MainWindow::judgeWin(){
    if(sum==3 && result == 24){
        scores++;
        ui->score->setText(QString::number(scores,10));
        sum=0;
        return true;
    }
    return false;
}

//将按钮隐藏或展示的函数
void MainWindow::openOrclose(int pre){
    switch (pre) {
        case 0:ui->num1->setVisible(true);ui->num2->setVisible(true);
               ui->num3->setVisible(true);ui->num4->setVisible(true);break;
        case 1:ui->num1->setVisible(false);break;
        case 2:ui->num2->setVisible(false);break;
        case 3:ui->num3->setVisible(false);break;
        case 4:ui->num4->setVisible(false);break;
    }
}

void MainWindow::on_num1_clicked()
{
    click->stop();
    click->play();
    if(resetflag)
    resetflag = false;
    if(countA==0 && countB==0 && !resetflag){
        //QString s = ((QPushButton*)sender())->text();
        QString s = ui->num1->text();
        countA = s.toInt();
        ui->num1->setEnabled(false);//选择后按钮不能被选择
        sum++;
        preButton=1;
    }
    else if(countA!=0 && countB==0){
        QString s = ui->num1->text();
        countB = s.toInt();
        switch (countC) {
            case '+':result = countA + countB;break;
            case '-':result = countA - countB;break;
            case '*':result = countA * countB;break;
            case '/':result = countA / countB;break;
        }
        ui->num1->setText(QString::number(result,10));
        openOrclose(preButton);
        countA=0;countB=0;
        if(judgeWin()){
            cal.setNum();
            on_reset_clicked();
        }
    }
}

void MainWindow::on_num2_clicked()
{
    click->stop();
    click->play();
    if(resetflag)
        resetflag = false;
    //如果前一个运算符未被选择，则选中该运算符
    if(countA==0 && countB==0 && !resetflag){
        QString s = ui->num2->text();
        countA = s.toInt();
        ui->num2->setEnabled(false);//选择后按钮不能被选择
        sum++;
        preButton=2;
    }
    else if(countA!=0 && countB==0){
        QString s = ui->num2->text();
        countB = s.toInt();
        switch (countC) {
            case '+':result = countA + countB;break;
            case '-':result = countA - countB;break;
            case '*':result = countA * countB;break;
            case '/':result = countA / countB;break;
        }
        ui->num2->setText(QString::number(result,10));
        openOrclose(preButton);
        countA=0;countB=0;
        if(judgeWin()){
            cal.setNum();
            on_reset_clicked();
        }
    }
}

void MainWindow::on_num3_clicked()
{
    click->stop();
    click->play();
    if(resetflag)
        resetflag = false;
    if(countA==0 && countB==0 && !resetflag){
        QString s = ui->num3->text();
        countA = s.toInt();
        ui->num3->setEnabled(false);//选择后按钮不能被选择
        sum++;
        preButton=3;
    }
    else if(countA!=0 && countB==0){
        QString s = ui->num3->text();
        countB = s.toInt();
        switch (countC) {
            case '+':result = countA + countB;break;
            case '-':result = countA - countB;break;
            case '*':result = countA * countB;break;
            case '/':result = countA / countB;break;
        }
        ui->num3->setText(QString::number(result,10));
        openOrclose(preButton);
        countA=0;countB=0;
        if(judgeWin()){
            cal.setNum();
            on_reset_clicked();
        }
    }
}

void MainWindow::on_num4_clicked()
{
    click->stop();
    click->play();
    if(resetflag)
        resetflag = false;
    if(countA==0 && countB==0 && !resetflag){
        QString s = ui->num4->text();
        countA = s.toInt();
        ui->num4->setEnabled(false);//选择后按钮不能被选择
        sum++;
        preButton=4;
    }
    else if(countA!=0 && countB==0){
        QString s = ui->num4->text();
        countB = s.toInt();
        switch (countC) {
            case '+':result = countA + countB;break;
            case '-':result = countA - countB;break;
            case '*':result = countA * countB;break;
            case '/':result = countA / countB;break;
        }
        ui->num4->setText(QString::number(result,10));
        openOrclose(preButton);
        countA=0;countB=0;
        if(judgeWin()){
            cal.setNum();
            on_reset_clicked();
        }
    }
}

void MainWindow::on_Btn5_clicked()
{
    click->stop();
    click->play();
    QString s = ui->Btn5->text();
    countC = s.at(0).toLatin1();
}

void MainWindow::on_Btn6_clicked()
{
    click->stop();
    click->play();
    QString s = ui->Btn6->text();
    countC = s.at(0).toLatin1();
}

void MainWindow::on_Btn7_clicked()
{
    click->stop();
    click->play();
    QString s = ui->Btn7->text();
    countC = s.at(0).toLatin1();
}

void MainWindow::on_Btn8_clicked()
{
    click->stop();
    click->play();
    QString s = ui->Btn8->text();
    countC = s.at(0).toLatin1();
}

void MainWindow::on_reset_clicked()
{
    //1.重置数字
    ui->num1->setText(QString::number(cal.getNum(0),10));
    ui->num2->setText(QString::number(cal.getNum(1),10));
    ui->num3->setText(QString::number(cal.getNum(2),10));
    ui->num4->setText(QString::number(cal.getNum(3),10));
    //2.重新打开按钮
    resetflag = true;
    ui->num1->setEnabled(true);
    ui->num2->setEnabled(true);
    ui->num3->setEnabled(true);
    ui->num4->setEnabled(true);
    //3.重新初始化countA、countB、sum
    countA = 0;countB = 0;sum = 0;preButton=0;
    openOrclose(preButton);
}

void MainWindow::doProcessAdRequest(bool flag1){
    videoFlag = flag1;
}

void MainWindow::on_tips_clicked()
{
    //如果还有次数则使用一次减一次
    if(answerTimes>0){
        cal.Answer();
        QString res = " ";
        for(int i=0;i<cal.getResultCount();i++){
            res += QString::fromStdString(cal.getResult(i));
            res+="    ";
            if((i+1)%4==0)
                res+='\n';
        }
        QMessageBox *qmb = new QMessageBox(this);
        qmb->setText(res);
        qmb->exec();
        qmb->setGeometry(0,0,540,300);
        QFont qf;qf.setPixelSize(11);
        qmb->setFont(qf);
        qmb->setWindowTitle("参考答案");
        answerTimes--;
        ui->label_time2->setText(QString::number(answerTimes));
    }
    //如果已经没有次数就不能再使用
    if(answerTimes==0){
        ui->tips->setEnabled(false);
    }
}

//重新发牌
void MainWindow::on_refresh_clicked()
{
    //如果还有次数则使用一次减一次
    if(refreshTimes>0){
        cal.setNum();
        on_reset_clicked();
        refreshTimes--;
        ui->label_time1->setText(QString::number(refreshTimes));
    }
    //如果已经没有次数就不能再使用
    if(refreshTimes==0){
        ui->refresh->setEnabled(false);
    }
}

void MainWindow::on_question_clicked()
{
    Question q;
    q.exec();
}

void MainWindow::on_btn_music_clicked()
{
    musicFlag = !musicFlag;
    if(musicFlag){
        player->play();
        ui->btn_music->setText("🔊");
    }
    else {
        player->stop();
        ui->btn_music->setText("🔇");
    }
}
